<template>
  <div class="filter-container">
    <!-- 跟进提醒通知区域 -->
    <div v-if="upcomingFollowUps.length > 0" class="reminder-notification">
      <a-alert
        :message="`您有 ${upcomingFollowUps.length} 个跟进任务即将到期`"
        type="warning"
        showIcon
        closable
        class="reminder-alert"
      >
        <template #description>
          <div class="upcoming-list">
            <div 
              v-for="item in upcomingFollowUps.slice(0, 3)" 
              :key="item.id" 
              class="upcoming-item"
              @click="scrollToRecord(item)"
            >
              <span class="customer-name">{{ item.customerName }}</span>
              <span class="due-time">{{ formatDueTime(item.nextFollowTime) }}</span>
            </div>
            <div v-if="upcomingFollowUps.length > 3" class="more-count">
              还有 {{ upcomingFollowUps.length - 3 }} 个...
            </div>
          </div>
        </template>
      </a-alert>
    </div>
    
    <!-- 客户跟进列表 -->
    <div class="section-title">客户跟进管理</div>
    <div class="filter-item">
      <a-input v-model:value="searchParams.customerName" placeholder="搜索客户" style="width: 200px; margin-right: 10px" />
      <a-select
        v-model:value="searchParams.followUpStatus"
        placeholder="跟进状态"
        style="width: 120px; margin-right: 10px"
        allowClear
      >
        <a-select-option v-for="option in followUpStatusOptions" :key="option.value" :value="option.value">
          {{ option.label }}
        </a-select-option>
      </a-select>
      <a-range-picker v-model:value="searchParams.dateRange" style="width: 300px" />
      <a-button type="primary" style="margin-left: 10px" @click="handleSearch">搜索</a-button>
      <a-button style="margin-left: 10px" @click="handleClear">清空</a-button>
      <a-button type="primary" style="margin-left: 10px" @click="handleAdd">新增跟进</a-button>
      <a-popconfirm v-if="selectedFollowUpKeys.length" title="确定要批量删除选中的记录吗？" ok-text="确定" cancel-text="取消" @confirm="handleBatchDelete">
        <a-button danger style="margin-left: 10px" :disabled="!selectedFollowUpKeys.length">批量删除</a-button>
      </a-popconfirm>
    </div>

    <div class="table-container">
      <a-table
        :dataSource="followUpList"
        :columns="followUpColumns"
        :rowKey="(record) => record.id"
        :pagination="pagination"
        :rowSelection="{
          type: 'checkbox',
          selectedRowKeys: selectedFollowUpKeys,
          onChange: onSelectFollowUp
        }"
        bordered
        :loading="loading"
        :rowClassName="(record, index) => (index % 2 === 1 ? 'table-row-light' : 'table-row-dark')"
        :scroll="{ x: 'max-content' }"
      >
        <template #action="{ record }">
          <a-button type="primary" size="small" @click="handleView(record)">查看</a-button>
          <a-tooltip v-if="!record?.deadLine" title="请设置跟进时限">
            <a-badge dot>
              <a-button type="primary" size="small" style="margin: 0 10px" @click="handleEdit(record)">编辑</a-button>
            </a-badge>
          </a-tooltip>
          <a-button type="primary" size="small" style="margin: 0 10px" @click="handleEdit(record)" v-auth = "'customers_pool:customers_pool:adddeveloper'">编辑</a-button>
          <a-button type="primary" size="small" style="margin: 0 10px"
            @click="openCreateOrderModal(record)"
            :disabled="record.followUpStatus !== '成交'"
          >创建订单</a-button>
          <a-popconfirm title="确定要删除吗？" ok-text="确定" cancel-text="取消" @confirm="handleDelete(record)">
            <a-button type="primary" danger size="small"v-auth = "'followup:follow_up:delete'">删除</a-button>
          </a-popconfirm>
        </template>
      </a-table>
    </div>

    <!-- 创建订单弹窗 -->
    <a-modal
      :title="createOrderTitle"
      :visible="createOrderModalVisible"
      :confirmLoading="createOrderSubmitting"
      @ok="handleConfirmCreateOrder"
      @cancel="() => (createOrderModalVisible = false)"
      :width="720"
      destroyOnClose
    >
      <a-alert type="info" show-icon style="margin-bottom: 12px" :message="`客户：${createOrderForm.customerName}，产品类别：${createOrderForm.productType}`" />
      <a-table
        :dataSource="createOrderItems"
        :pagination="false"
        :rowKey="(row, idx) => idx"
        bordered
      >
        <a-table-column title="产品名称">
          <template #default="{ record }">{{ record.productName }}</template>
        </a-table-column>
        <a-table-column title="单位">
          <template #default="{ record, index }">
            <a-input :value="record.unit" style="width:120px" @change="(e) => (createOrderItems[index].unit = e && e.target ? e.target.value : '')" />
          </template>
        </a-table-column>
        <a-table-column title="数量">
          <template #default="{ record, index }">
            <a-input-number :value="record.quantity" :min="1" style="width:120px" @change="(val) => (createOrderItems[index].quantity = val || 1)" />
          </template>
        </a-table-column>
      </a-table>
    </a-modal>

    <!-- 子表区域 -->
    <div class="subtables-container" v-if="selectedFollowUpRecord">
      <div class="section-title">{{ selectedFollowUpRecord.customerName }} 的跟进信息</div>
      <a-tabs v-model:activeKey="activeSubTab">
        <!-- 跟进记录子表 -->
        <a-tab-pane key="content" tab="跟进记录">
          <div class="filter-item">
            <a-button type="primary" @click="handleAddContent" :disabled="!selectedFollowUpRecord">新增记录</a-button>
            <a-button type="default" @click="handleUpdateFollowUpStatus" :disabled="!selectedFollowUpRecord" style="margin-left: 8px;">修改跟进状态</a-button>
          </div>

          <div class="table-container">
            <a-table
              :dataSource="followContentList"
              :columns="followContentColumns"
              :rowKey="(record) => record.id"
              :pagination="contentPagination"
              bordered
              :loading="contentLoading"
              :rowClassName="(record, index) => (index % 2 === 1 ? 'table-row-light' : 'table-row-dark')"
              :scroll="{ x: 'max-content' }"
            >
              <template #followUpContentFile>
                <span>-</span>
              </template>
              <template #action="{ record }">
                <a-button type="primary" size="small" @click="handleViewContent(record)">查看</a-button>
                <a-button type="primary" size="small" style="margin: 0 10px" @click="handleEditContent(record)">编辑</a-button>

                <a-popconfirm title="确定要删除吗？" ok-text="确定" cancel-text="取消" @confirm="handleDeleteContent(record)">
                  <a-button type="primary" danger size="small" style="margin-left: 10px">删除</a-button>
                </a-popconfirm>
              </template>
            </a-table>
          </div>
        </a-tab-pane>

        <!-- 跟进计划子表 -->


        <!-- 需求人员子表 -->
        <a-tab-pane key="requirementPerson" tab="跟进人员表">
          <div class="filter-item">
            <a-button type="primary" @click="handleAddRequirementPerson" :disabled="!selectedFollowUpRecord" v-auth="'customers_pool:customers_pool:adddeveloper'">新增跟进人员</a-button>
          </div>
          <div class="table-container">
            <a-table
              :dataSource="requirementPersonList"
              :columns="requirementPersonColumns"
              :rowKey="(record) => record.id || record.email"
              :pagination="requirementPersonPagination"
              bordered
              :loading="requirementPersonLoading"
              :rowClassName="(record, index) => (index % 2 === 1 ? 'table-row-light' : 'table-row-dark')"
              :scroll="{ x: 'max-content' }"
            >
              <template #requirementPersonAction="{ record }">
                <a-popconfirm title="确定要删除吗？" ok-text="确定" cancel-text="取消" @confirm="handleDeleteRequirementPerson(record)">
                  <a-button type="primary" danger size="small" v-auth="'developers:developers:delete'">删除</a-button>
                </a-popconfirm>
              </template>
            </a-table>
          </div>
        </a-tab-pane>
      </a-tabs>
    </div>
    <div class="empty-subtables" v-else>
      <a-empty description="请选择一条客户跟进记录查看详细信息" />
    </div>

    <!-- 客户跟进模态框 -->
    <a-modal v-model:visible="followUpModalVisible" :title="followUpModalTitle" :width="800" @ok="handleFollowUpSave" :confirmLoading="loading">
      <a-form ref="followUpFormRef" :model="currentFollowUp" :rules="followUpFormRules" layout="vertical">
        <a-row :gutter="16">
          <a-col :span="24">
            <a-form-item label="客户" name="customerId">
              <a-select
                v-model:value="currentFollowUp.customerId"
                placeholder="请选择客户"
                :loading="customerLoading"
                @change="handleCustomerChange"
                show-search
                :filter-option="(input, option) => option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0"
              >
                <a-select-option v-for="customer in customerList" :key="customer.id" :value="customer.id" :label="customer.customerName">
                  {{ customer.customerName }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="产品类别" name="productType">
              <a-select
                v-model:value="currentFollowUp.productType"
                placeholder="请选择产品类别"
                :loading="productTypeLoading"
                @change="handleProductTypeChange"
                show-search
                :filter-option="(input, option) => option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0"
                :disabled="isEditMode"
              >
                <a-select-option v-for="type in productTypeList" :key="type.id" :value="type.id" :label="type.productType">
                  {{ type.productType }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="产品名称" name="productNameIds">
              <a-select
                v-model:value="currentFollowUp.productNameIds"
                mode="multiple"
                placeholder="请选择产品名称（可多选）"
                :loading="productNameLoading"
                @change="handleProductNameChange"
                show-search
                :filter-option="(input, option) => option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0"
                :disabled="isEditMode || !currentFollowUp.productTypeId"
                :max-tag-count="2"
                :max-tag-text-length="10"
              >
                <a-select-option v-for="product in productNameList" :key="product.id" :value="product.id" :label="product.productName">
                  {{ product.productName }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="跟进限时(天)" name="deadLine">
              <a-input-number v-model:value="currentFollowUp.deadLine" style="width: 100%" placeholder="请输入跟进限时天数" :min="1" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="跟进状态" name="followUpStatus">
              <a-select
                v-model:value="currentFollowUp.followUpStatus"
                placeholder="请选择跟进状态"
              >
                <a-select-option v-for="option in followUpStatusOptions" :key="option.value" :value="option.value">
                  {{ option.label }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="注册资本(万元)" name="registeredCapital">
              <a-input v-model:value="currentFollowUp.registeredCapital" placeholder="请输入注册资本（万元）" :allow-clear="!isView" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="行业" name="industry">
              <a-input v-model:value="currentFollowUp.industry" placeholder="请输入行业" :allow-clear="!isView" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="16">
          <a-col :span="24">
            <a-form-item label="经营范围" name="bussinessScope">
              <a-textarea v-model:value="currentFollowUp.bussinessScope" placeholder="请输入经营范围" :rows="3" :allow-clear="!isView" />
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>

      <template #footer>
        <a-button @click="followUpModalVisible = false">取消</a-button>
        <a-button v-if="!isView" type="primary" @click="handleFollowUpSave" :loading="loading">保存</a-button>
      </template>
    </a-modal>



    <!-- 跟进记录模态框 - 美化版本 -->
    <a-modal v-model:visible="contentModalVisible" :title="contentModalTitle" :width="1200" @ok="handleContentSave" :confirmLoading="contentLoading" class="follow-up-modal">
      <div class="modal-content-wrapper">
        <a-form ref="contentFormRef" :model="currentContent" :rules="contentFormRules" layout="vertical" class="follow-up-form">
          <!-- 基础信息卡片 -->
          <a-card title="基础信息" class="form-section-card" :bordered="false">
            <a-row :gutter="24">
              <a-col :span="8">
                <a-form-item label="客户分类" name="customerClassification">
                  <a-select v-model:value="currentContent.customerClassification" placeholder="请选择客户分类" :disabled="isView" class="custom-select">
                    <a-select-option value="A类">
                      <span class="select-option-content">
                        <a-tag color="red">A类</a-tag>
                        重点客户
                      </span>
                    </a-select-option>
                    <a-select-option value="B类">
                      <span class="select-option-content">
                        <a-tag color="orange">B类</a-tag>
                        一般客户
                      </span>
                    </a-select-option>
                    <a-select-option value="C类">
                      <span class="select-option-content">
                        <a-tag color="blue">C类</a-tag>
                        潜在客户
                      </span>
                    </a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item label="意向度" name="intention">
                  <a-select v-model:value="currentContent.intention" placeholder="请选择意向度" :disabled="isView" class="custom-select">
                    <a-select-option value="低">
                      <span class="select-option-content">
                        <a-tag color="red">低</a-tag>
                        意向度较低
                      </span>
                    </a-select-option>
                    <a-select-option value="中">
                      <span class="select-option-content">
                        <a-tag color="orange">中</a-tag>
                        意向度一般
                      </span>
                    </a-select-option>
                    <a-select-option value="高">
                      <span class="select-option-content">
                        <a-tag color="green">高</a-tag>
                        意向度很高
                      </span>
                    </a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item label="下次跟进时间" name="nextFollowTime">
                  <a-date-picker 
                    v-model:value="currentContent.nextFollowTime" 
                    style="width: 100%" 
                    placeholder="请选择下次跟进时间" 
                    :disabled="isView"
                    :show-time="{ format: 'HH:mm' }"
                    format="YYYY-MM-DD HH:mm"
                    class="custom-date-picker"
                  />
                </a-form-item>
              </a-col>
            </a-row>
          </a-card>

          <!-- 需求信息卡片 -->
          <a-card title="需求信息" class="form-section-card" :bordered="false">
            <a-row :gutter="24">
              <a-col :span="12">
                <a-form-item label="产品需求" name="requirment">
                  <a-textarea 
                    v-model:value="currentContent.requirment" 
                    placeholder="请详细描述客户的产品需求，包括功能要求、技术规格等..." 
                    :rows="4" 
                    :disabled="isView"
                    class="custom-textarea"
                    :maxlength="500"
                    show-count
                  />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="潜在产品需求" name="potentialRequirment">
                  <a-textarea 
                    v-model:value="currentContent.potentialRequirment" 
                    placeholder="请描述客户可能存在的潜在需求和未来可能的业务拓展方向..." 
                    :rows="4" 
                    :disabled="isView"
                    class="custom-textarea"
                    :maxlength="500"
                    show-count
                  />
                </a-form-item>
              </a-col>
            </a-row>
          </a-card>

          <!-- 时间确认信息 -->
          <a-card title="服务时间" class="form-section-card" :bordered="false">
            <a-row :gutter="24">
              <a-col :span="24">
                <a-form-item label="代理记账到期时间确认" name="timeConfirm">
                  <a-select v-model:value="currentContent.timeConfirm" placeholder="请选择代理记账到期月份" :disabled="isView" class="custom-select">
                    <a-select-option v-for="month in 12" :key="month" :value="`${month}月`">
                      <span class="select-option-content">
                        <Icon icon="ant-design:calendar-outlined" />
                        {{ month }}月
                      </span>
                    </a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
            </a-row>
          </a-card>

          <!-- 跟进详情卡片 -->
          <a-card title="跟进详情" class="form-section-card" :bordered="false">
            <a-row :gutter="24">
              <a-col :span="24">
                <a-form-item label="其他跟进事项描述" name="otherDescription">
                  <a-textarea 
                    v-model:value="currentContent.otherDescription" 
                    placeholder="请输入其他需要跟进的事项或特殊说明..." 
                    :rows="3" 
                    :disabled="isView"
                    class="custom-textarea"
                    :maxlength="300"
                    show-count
                  />
                </a-form-item>
              </a-col>
            </a-row>
            <a-row :gutter="24">
              <a-col :span="24">
                <a-form-item label="跟进记录描述" name="followUpDescription">
                  <a-textarea 
                    v-model:value="currentContent.followUpDescription" 
                    placeholder="请详细记录本次跟进的具体内容、沟通要点、客户反馈等..." 
                    :rows="4" 
                    :disabled="isView"
                    class="custom-textarea"
                    :maxlength="1000"
                    show-count
                  />
                </a-form-item>
              </a-col>
            </a-row>
            <a-row :gutter="24">
              <a-col :span="24">
                <a-form-item label="面谈总结" name="summarize">
                  <a-textarea 
                    v-model:value="currentContent.summarize" 
                    placeholder="请总结本次面谈的核心要点、达成的共识、待解决问题等..." 
                    :rows="4" 
                    :disabled="isView"
                    class="custom-textarea"
                    :maxlength="800"
                    show-count
                  />
                </a-form-item>
              </a-col>
            </a-row>
          </a-card>

          <!-- 评价与意见卡片 -->
          <a-card title="评价与意见" class="form-section-card" :bordered="false">
            <a-row :gutter="24">
              <a-col :span="24">
                <a-form-item label="管理评价" name="managementOpinion">
                  <a-textarea 
                    v-model:value="currentContent.managementOpinion" 
                    placeholder="请输入管理层对本次跟进的评价和建议..." 
                    :rows="3" 
                    :disabled="isView"
                    class="custom-textarea"
                    :maxlength="500"
                    show-count
                  />
                </a-form-item>
              </a-col>
            </a-row>
            <a-row :gutter="24">
              <a-col :span="12">
                <a-form-item label="商务复查意见" name="businessOpinion">
                  <a-textarea 
                    v-model:value="currentContent.businessOpinion" 
                    placeholder="请输入商务部门的复查意见和后续建议..." 
                    :rows="3" 
                    :disabled="isView"
                    class="custom-textarea"
                    :maxlength="400"
                    show-count
                  />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="技术支持记录" name="technologyRecord">
                  <a-textarea 
                    v-model:value="currentContent.technologyRecord" 
                    placeholder="请记录技术支持相关的内容和解决方案..." 
                    :rows="3" 
                    :disabled="isView"
                    class="custom-textarea"
                    :maxlength="400"
                    show-count
                  />
                </a-form-item>
              </a-col>
            </a-row>
          </a-card>
        </a-form>
      </div>

      <template #footer>
        <div class="modal-footer-wrapper">
          <a-button size="large" @click="contentModalVisible = false" class="cancel-btn">
            <Icon icon="ant-design:close-outlined" />
            取消
          </a-button>
          <a-button v-if="!isView" type="primary" size="large" @click="handleContentSave" :loading="contentLoading" class="save-btn">
            <Icon icon="ant-design:save-outlined" />
            保存
          </a-button>
        </div>
      </template>
    </a-modal>

    <!-- 文件上传模态框 -->
    <a-modal v-model:visible="fileUploadModalVisible" :title="fileUploadTitle" :width="600" :footer="null">
      <div class="file-upload-container">
        <a-upload-dragger
          v-model:fileList="fileUploadList"
          :multiple="true"
          :showUploadList="{
            showPreviewIcon: true,
            showRemoveIcon: true,
            showDownloadIcon: true,
          }"
          name="file"
          :headers="{ 'X-Access-Token': userStore.getToken }"
          :before-upload="handleBeforeUploadFile"
          :customRequest="customUploadFile"
          @remove="handleRemoveFile"
        >
          <p class="ant-upload-drag-icon">
            <Icon icon="ant-design:cloud-upload-outlined" style="font-size: 40px; color: #40a9ff" />
          </p>
          <p class="ant-upload-text">点击或拖拽文件到此处上传</p>
          <p class="ant-upload-hint">支持多文件上传，单个文件不超过10M</p>
        </a-upload-dragger>

        <div class="file-upload-actions">
          <a-button @click="fileUploadModalVisible = false">关闭</a-button>
          <a-button type="primary" @click="handleFileUploadComplete">完成</a-button>
        </div>
      </div>
    </a-modal>

    <!-- 文件详情模态框 -->
    <a-modal v-model:visible="fileDetailModalVisible" title="文件详情" :width="800" :footer="null">
      <div class="file-detail-container">
        <a-table
          :dataSource="currentFiles"
          :columns="fileColumns"
          :rowKey="(record) => record.id"
          :pagination="false"
          size="small"
        >
          <template #action="{ record }">
            <a-button type="link" size="small" @click="handlePreviewFile(record)">预览</a-button>
            <a-button type="link" size="small" @click="handleDownloadFile(record)">下载</a-button>
            <a-popconfirm title="确定要删除吗？" ok-text="确定" cancel-text="取消" @confirm="handleDeleteFile(record)">
              <a-button type="link" size="small" danger>删除</a-button>
            </a-popconfirm>
          </template>
        </a-table>
      </div>
    </a-modal>

    <!-- 创建合同模态框 -->
    <a-modal v-model:visible="projectModalVisible" title="创建合同" :width="600" @ok="handleProjectSave" :confirmLoading="projectLoading">
      <a-form ref="projectFormRef" :model="projectForm" layout="vertical">
        <a-form-item label="合同主题" name="contractTheme" :rules="[{ required: true, message: '请输入合同主题' }]">
          <a-input v-model:value="projectForm.contractTheme" placeholder="请输入合同主题" />
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 修改跟进状态模态框 -->
    <a-modal v-model:visible="updateStatusModalVisible" title="修改跟进状态" :width="400" @ok="handleUpdateStatusSave" :confirmLoading="updateStatusLoading">
      <a-form ref="updateStatusFormRef" :model="updateStatusForm" :rules="updateStatusFormRules" layout="vertical">
        <a-form-item label="跟进状态" name="followUpStatus">
          <a-select v-model:value="updateStatusForm.followUpStatus" placeholder="请选择跟进状态">
            <a-select-option value="60">60</a-select-option>
            <a-select-option value="80">80</a-select-option>
            <a-select-option value="100">100</a-select-option>
            <a-select-option value="成交">成交</a-select-option>
          </a-select>
        </a-form-item>
      </a-form>

      <template #footer>
        <a-button @click="updateStatusModalVisible = false">取消</a-button>
        <a-button type="primary" @click="handleUpdateStatusSave" :loading="updateStatusLoading">确定</a-button>
      </template>
    </a-modal>

    <!-- 需求人员模态框 -->
    <a-modal v-model:visible="requirementPersonModalVisible" :title="requirementPersonModalTitle" :width="600" @ok="handleRequirementPersonSave" :confirmLoading="requirementPersonLoading">
      <a-form ref="requirementPersonFormRef" :model="requirementPersonForm" :rules="requirementPersonFormRules" layout="vertical">
        <a-form-item label="选择部门" name="departId">
          <a-select
            v-model:value="requirementPersonForm.departId"
            placeholder="请选择部门"
            @change="handleDepartmentChange"
            show-search
            :filter-option="(input, option) => option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0"
          >
            <a-select-option v-for="dept in departList" :key="dept.id" :value="dept.id" :label="dept.departName">
              {{ dept.departName }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="选择人员" name="userId">
          <a-select
            v-model:value="requirementPersonForm.userId"
            placeholder="请选择人员"
            @change="handleUserChange"
            show-search
            :filter-option="(input, option) => option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0"
            :disabled="!requirementPersonForm.departId"
          >
            <a-select-option v-for="user in userList" :key="user.id" :value="user.id" :label="user.realname">
              {{ user.realname }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="选择角色" name="developRole">
          <a-select
            v-model:value="requirementPersonForm.developRole"
            placeholder="请选择角色"
          >
            <a-select-option v-for="role in roleOptions" :key="role.value" :value="role.value">
              {{ role.label }}
            </a-select-option>
          </a-select>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup>
import { message } from 'ant-design-vue';
import { ref, reactive, onMounted, computed, nextTick, h } from 'vue';
import { getAppEnvConfig } from '/@/utils/env';
import axios from 'axios';
import dayjs from 'dayjs';
import { useUserStore } from '/@/store/modules/user';
import { Icon } from '/@/components/Icon';
import { JDictSelectTag } from '/@/components/Form';
import { assignBusinessDeptUser2 } from '../customers_pool/CustomersPool.api';
// 注册组件
const components = {
  JDictSelectTag,
};

// 用户信息
const userStore = useUserStore();

// 当前激活的标签页
const activeTab = ref('followup');

// 搜索参数
const searchParams = ref({
  customerName: '',
  followUpStatus: undefined,
  dateRange: [],
});

// 加载状态
const loading = ref(false);
const contentLoading = ref(false);
const projectLoading = ref(false); // 新增：创建合同加载状态
const requirementPersonLoading = ref(false); // 需求人员加载状态
const updateStatusLoading = ref(false); // 修改跟进状态加载状态

// 数据列表
const followUpList = ref([]);
const followContentList = ref([]);
const requirementPersonList = ref([]);
const upcomingFollowUps = ref([]); // 即将到期的跟进记录

// 分页配置
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showTotal: (total) => `共 ${total} 条记录`,
  onChange: (page, pageSize) => {
    pagination.current = page;
    pagination.pageSize = pageSize;
    fetchFollowUpList();
  },
  onShowSizeChange: (current, size) => {
    pagination.current = 1;
    pagination.pageSize = size;
    fetchFollowUpList();
  },
  pageSizeOptions: ['10', '20', '30', '50'],
});



const contentPagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showTotal: (total) => `共 ${total} 条记录`,
  pageSizeOptions: ['10', '20', '30', '50'],
});

const requirementPersonPagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showTotal: (total) => `共 ${total} 条记录`,
  pageSizeOptions: ['10', '20', '30', '50'],
});

// 表格列定义
const followUpColumns = [
  {
    title: '序号',
    dataIndex: 'index',
    width: 60,
    customRender: ({ index }) => index + 1,
  },
  {
    title: '客户',
    dataIndex: 'customerName',
    width: 120,
  },
  {
    title: '产品类别',
    dataIndex: 'productType',
    width: 100,
  },
  {
    title: '产品名称',
    dataIndex: 'productName',
    width: 150,
    ellipsis: true,
    customRender: ({ text }) => {
      if (!text) return '-';

      // 如果是字符串，使用通用函数处理
      if (typeof text === 'string') {
        console.log('列表显示原始产品名称数据:', text);
        const names = processProductNameString(text);
        return names.join(', ');
      }

      // 如果是数组，显示为逗号分隔的字符串
      if (Array.isArray(text)) {
        return text.join(', ');
      }

      return text || '-';
    },
  },
  {
    title: '跟进限时(天)',
    dataIndex: 'deadLine',
    width: 120,
    customRender: ({ text }) => {
      return text ? `${text} 天` : '';
    },
  },
  {
    title: '跟进状态',
    dataIndex: 'followUpStatus',
    width: 100,
  },
  {
    title: '注册资本(万元)',
    dataIndex: 'registeredCapital',
    width: 140,
    customRender: ({ text }) => (text ? `${text} 万元` : ''),
  },
  {
    title: '行业',
    dataIndex: 'industry',
    width: 100,
  },
  {
    title: '经营范围',
    dataIndex: 'bussinessScope',
    width: 150,
    ellipsis: true,
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    width: 120,
    customRender: ({ text }) => {
      return text ? dayjs(text).format('YYYY-MM-DD') : '';
    },
  },
  {
    title: '操作',
    key: 'action',
    width: 200,
    fixed: 'right',
    slots: { customRender: 'action' },
  },
];



const followContentColumns = [
  {
    title: '序号',
    dataIndex: 'index',
    width: 60,
    customRender: ({ index }) => index + 1,
  },
  {
    title: '客户分类',
    dataIndex: 'customerClassification',
    width: 100,
  },
  {
    title: '意向度',
    dataIndex: 'intention',
    width: 80,
  },
  {
    title: '产品需求',
    dataIndex: 'requirment',
    width: 120,
    ellipsis: true,
  },
  {
    title: '潜在产品需求',
    dataIndex: 'potentialRequirment',
    width: 120,
    ellipsis: true,
  },
  {
    title: '下次跟进时间',
    dataIndex: 'nextFollowTime',
    width: 150,
    customRender: ({ text, record }) => {
      if (!text) return '';
      
      const followTime = dayjs(text);
      const now = dayjs();
      const daysLeft = followTime.diff(now, 'day');
      
      let color = '';
      let urgencyText = '';
      
      if (daysLeft < 0) {
        color = '#ff4d4f'; // 红色 - 已过期
        urgencyText = '已过期';
      } else if (daysLeft === 0) {
        color = '#fa8c16'; // 橙色 - 今天到期
        urgencyText = '今天';
      } else if (daysLeft <= 3) {
        color = '#faad14'; // 黄色 - 3天内到期
        urgencyText = `${daysLeft}天后`;
      } else {
        color = '#52c41a'; // 绿色 - 正常
        urgencyText = '';
      }
      
      return h('div', {
        style: {
          color: color,
          fontWeight: daysLeft <= 3 ? 'bold' : 'normal'
        }
      }, [
        h('div', followTime.format('YYYY-MM-DD')),
        urgencyText && h('div', {
          style: {
            fontSize: '12px',
            color: color
          }
        }, urgencyText)
      ]);
    },
  },
  {
    title: '跟进记录描述',
    dataIndex: 'followUpDescription',
    width: 150,
    ellipsis: true,
  },
  {
    title: '面谈总结',
    dataIndex: 'summarize',
    width: 120,
    ellipsis: true,
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    width: 120,
    customRender: ({ text }) => {
      return text ? dayjs(text).format('YYYY-MM-DD') : '';
    },
  },
  {
    title: '操作',
    key: 'action',
    width: 250,
    fixed: 'right',
    slots: { customRender: 'action' },
  },
];

// 需求人员表格列定义
const requirementPersonColumns = [
  {
    title: '序号',
    dataIndex: 'index',
    width: 60,
    customRender: ({ index }) => index + 1,
  },
  {
    title: '角色',
    dataIndex: 'developRole',
    width: 120,
    align: 'center',
    customRender: ({ text }) => text || '无角色',
  },
  {
    title: '邮箱',
    dataIndex: 'email',
    width: 180,
    align: 'center',
    customRender: ({ text }) => text || '无邮箱',
  },
  {
    title: '业务人员',
    dataIndex: 'developerName',
    width: 120,
    align: 'center',
    customRender: ({ text }) => text || '无创建人',
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    width: 150,
    align: 'center',
    customRender: ({ text }) => {
      return text ? dayjs(text).format('YYYY-MM-DD HH:mm:ss') : '无创建时间';
    },
  },
  {
    title: '更新人',
    dataIndex: 'updateBy',
    width: 120,
    align: 'center',
    customRender: ({ text }) => text || '无更新人',
  },
  {
    title: '更新时间',
    dataIndex: 'updateTime',
    width: 150,
    align: 'center',
    customRender: ({ text }) => {
      return text ? dayjs(text).format('YYYY-MM-DD HH:mm:ss') : '无更新时间';
    },
  },
  {
    title: '所属部门',
    dataIndex: 'sysOrgCode',
    width: 150,
    align: 'center',
    customRender: ({ text }) => text || '无所属部门',
  },
  {
    title: '操作',
    key: 'action',
    width: 80,
    fixed: 'right',
    slots: { customRender: 'requirementPersonAction' },
  },
];

const fileColumns = [
  {
    title: '文件名',
    dataIndex: 'fileName',
    width: 200,
    ellipsis: true,
  },
  {
    title: '文件大小',
    dataIndex: 'fileSize',
    width: 100,
    customRender: ({ text }) => {
      if (!text) return '';
      const size = parseInt(text);
      if (size < 1024) return size + 'B';
      if (size < 1024 * 1024) return (size / 1024).toFixed(2) + 'KB';
      return (size / (1024 * 1024)).toFixed(2) + 'MB';
    },
  },
  {
    title: '上传时间',
    dataIndex: 'createTime',
    width: 150,
    customRender: ({ text }) => {
      return text ? dayjs(text).format('YYYY-MM-DD HH:mm:ss') : '';
    },
  },
  {
    title: '操作',
    key: 'action',
    width: 150,
    slots: { customRender: 'action' },
  },
];

// 模态框状态
const followUpModalVisible = ref(false);
const contentModalVisible = ref(false);
const fileUploadModalVisible = ref(false);
const fileDetailModalVisible = ref(false);
const projectModalVisible = ref(false); // 新增：创建合同模态框状态
const requirementPersonModalVisible = ref(false); // 需求人员模态框状态
const updateStatusModalVisible = ref(false); // 修改跟进状态模态框状态

// 模态框标题
const followUpModalTitle = ref('');
const contentModalTitle = ref('');
const fileUploadTitle = ref('');
const projectModalTitle = ref('创建合同'); // 新增：创建合同模态框标题
const requirementPersonModalTitle = ref('新增需求人员'); // 需求人员模态框标题

// 是否为查看模式
const isView = ref(false);
// 编辑模式标识：编辑时禁用产品类别和产品名称
const isEditMode = ref(false);

// 当前编辑的数据
const currentFollowUp = ref({});
const currentContent = ref({});
const projectForm = ref({}); // 新增：创建合同表单数据
const requirementPersonForm = ref({}); // 需求人员表单数据
const updateStatusForm = ref({}); // 修改跟进状态表单数据

// 选中的跟进记录ID
const selectedFollowUpId = ref('');
const selectedFollowUpIdForContent = ref('');
const selectedFollowUpKeys = ref([]); // 新增：选中的客户跟进记录Keys
const selectedFollowUpRecord = ref(null); // 新增：选中的客户跟进记录对象
const activeSubTab = ref('content'); // 修改：默认选中跟进记录标签页

// 文件相关
const currentFiles = ref([]);
const fileUploadList = ref([]);
const currentUploadType = ref(''); // 'plan' 或 'content'
const currentUploadRecordId = ref('');

// 产品相关
const productTypeList = ref([]); // 产品类别列表
const productNameList = ref([]); // 产品名称列表
const productTypeLoading = ref(false); // 产品类别加载状态
const productNameLoading = ref(false); // 产品名称加载状态

// 客户相关
const customerList = ref([]); // 客户列表
const customerLoading = ref(false); // 客户加载状态

// 跟进状态选项
const followUpStatusOptions = [
  { value: '60', label: '60' },
  { value: '80', label: '80' },
  { value: '100', label: '100' },
  { value: '成交', label: '成交' },
];

// 表单引用
const followUpFormRef = ref();
const contentFormRef = ref();
const projectFormRef = ref(); // 新增：创建合同表单引用
const requirementPersonFormRef = ref(); // 需求人员表单引用
const updateStatusFormRef = ref(); // 修改跟进状态表单引用

// 表单验证规则
const followUpFormRules = {
  customerId: [{ required: true, message: '请选择客户', trigger: 'change' }],
  productTypeId: [{ required: true, message: '请选择产品类别', trigger: 'change' }],
  productNameIds: [{ required: true, message: '请选择产品名称', trigger: 'change' }],
  followUpStatus: [{ required: true, message: '请选择跟进状态', trigger: 'change' }],
};



const contentFormRules = {
  customerClassification: [{ required: true, message: '请选择客户分类', trigger: 'change' }],
  followUpDescription: [{ required: true, message: '请输入跟进记录描述', trigger: 'blur' }],
};

const requirementPersonFormRules = {
  departId: [{ required: true, message: '请选择部门', trigger: 'change' }],
  userId: [{ required: true, message: '请选择人员', trigger: 'change' }],
  developRole: [{ required: true, message: '请选择角色', trigger: 'change' }],
};

const updateStatusFormRules = {
  followUpStatus: [{ required: true, message: '请选择跟进状态', trigger: 'change' }],
};

// 客户标签选项 - 现在使用字典配置

// API基础URL
const { VITE_GLOB_API_URL } = getAppEnvConfig();
const API_BASE = `${VITE_GLOB_API_URL}/followup/followUp`;

// API方法
const api = {
  // 客户跟进相关
  list: `${API_BASE}/list`,
  add: `${API_BASE}/add`,
  edit: `${API_BASE}/edit`,
  editFollowStatus: `${API_BASE}/editFollowStatus`,
  delete: `${API_BASE}/delete`,
  
  // 产品相关
  getProductTypes: '/jeecg-boot/products/productType/getProductTypeNameAndId',
  getProductName: '/jeecg-boot/products/productType/getProductNameByProductTypeId',
  
  // 客户相关
  getCustomers: '/jeecg-boot/customers_pool/customersPool/getCustomerNameAndId',
  
  // 需求人员相关
  getRequirementPersonList: `/jeecg-boot/developers/developers/getdeveloperecpreq`,
  editRequirementPerson: `/jeecg-boot/developers/developers/edit`,
  deleteRequirementPerson: `/jeecg-boot/developers/developers/delete`,
  getAllDepart: `/jeecg-boot/sys/sysDepart/getAllDepart`,
  getUserByDepartId: `/jeecg-boot/sys/sysDepart/getUsersByDepartId`,



  // 跟进记录相关
  followUpContentList: `${API_BASE}/queryFollowUpContentByMainId`,
  addFollowUpContent: `${API_BASE}/addFollowUpContent`,
  editFollowUpContent: `${API_BASE}/editFollowUpContent`,
  deleteFollowUpContent: `${API_BASE}/deleteFollowUpContent`,
  upcomingFollowUps: `${API_BASE}/upcoming-followups`,
  checkOverdueFollowUps: `${API_BASE}/checkOverdueFollowUps`,
  processOverdueAndReturnToPool: `${API_BASE}/processOverdueAndReturnToPool`,
  manualProcessReturn: `${API_BASE}/manualProcessReturn`,

  // 文件相关
  uploadFollowPlanFile: `${API_BASE}/uploadFollowPlanFile`,
  uploadFollowUpFile: `${API_BASE}/uploadFollowUpFile`,
  getFollowPlanFiles: `${API_BASE}/getFollowPlanFiles`,
  downloadFile: `${API_BASE}/downloadFile`,
  deleteFile: `${API_BASE}/deleteFile`,
  previewFile: `${API_BASE}/previewFile`,

  // 创建合同接口
  followUpGenerateContract: `/jeecg-boot/contracts/contracts/followUpGenerateContract`,
};

// 获取客户跟进列表
const fetchFollowUpList = async () => {
  try {
    loading.value = true;
    const params = {
      pageNo: pagination.current,
      pageSize: pagination.pageSize,
      ...searchParams.value,
    };

    if (searchParams.value.dateRange && searchParams.value.dateRange.length === 2) {
      params.createTime_begin = dayjs(searchParams.value.dateRange[0]).format('YYYY-MM-DD');
      params.createTime_end = dayjs(searchParams.value.dateRange[1]).format('YYYY-MM-DD');
    }

    const response = await axios.get(api.list, {
      params,
      headers: { 'X-Access-Token': userStore.getToken },
    });

    if (response.data.success) {
      followUpList.value = response.data.result.records || [];
      pagination.total = response.data.result.total || 0;
      // 控制台输出主表（客户跟进）列表信息
      console.log('主表（客户跟进）列表信息:', followUpList.value);
    } else {
      message.error(response.data.message || '获取数据失败');
    }
  } catch (error) {
    
    message.error('获取数据失败');
  } finally {
    loading.value = false;
  }
};

// 获取即将到期的跟进记录
const fetchUpcomingFollowUps = async (days = 3) => {
  try {
    const response = await axios.get(api.upcomingFollowUps, {
      params: { days },
      headers: { 'X-Access-Token': userStore.getToken },
    });

    if (response.data.success) {
      upcomingFollowUps.value = response.data.result || [];
      console.log('即将到期的跟进记录:', upcomingFollowUps.value);
    } else {
      console.error('获取即将到期跟进记录失败:', response.data.message);
    }
  } catch (error) {
    console.error('获取即将到期跟进记录失败:', error);
  }
};

// 格式化到期时间显示
const formatDueTime = (dateTime) => {
  if (!dateTime) return '';
  
  const followTime = dayjs(dateTime);
  const now = dayjs();
  const daysLeft = followTime.diff(now, 'day');
  
  if (daysLeft < 0) {
    return `已过期 ${Math.abs(daysLeft)} 天`;
  } else if (daysLeft === 0) {
    return '今天到期';
  } else if (daysLeft === 1) {
    return '明天到期';
  } else {
    return `${daysLeft} 天后到期`;
  }
};

// 滚动到指定记录
const scrollToRecord = (item) => {
  // 这里可以实现滚动到对应记录的逻辑
  console.log('点击查看即将到期记录:', item);
  // 可以选中对应的跟进记录并展开详情
  const targetRecord = followUpList.value.find(record => record.id === item.followUpId);
  if (targetRecord) {
    selectedFollowUpKeys.value = [targetRecord.id];
    selectedFollowUpRecord.value = targetRecord;
    onSelectFollowUp([targetRecord.id], [targetRecord]);
    // 切换到跟进记录tab
    activeSubTab.value = 'content';
  }
};

// 选中客户跟进记录
const onSelectFollowUp = (selectedRowKeys, selectedRows) => {
  selectedFollowUpKeys.value = selectedRowKeys;
  if (selectedRows && selectedRows.length > 0) {
    selectedFollowUpRecord.value = selectedRows[0];
    console.log('选中的跟进记录:', selectedFollowUpRecord.value);
    // 加载子表数据
    loadFollowContents();
    loadRequirementPersons();
  } else {
    selectedFollowUpRecord.value = null;
    // 清空子表数据
    followContentList.value = [];
    requirementPersonList.value = [];
  }
};

// 批量删除
const handleBatchDelete = async () => {
  if (!selectedFollowUpKeys.value || !selectedFollowUpKeys.value.length) {
    message.warning('请先选择要删除的记录');
    return;
  }
  try {
    loading.value = true;
    const ids = selectedFollowUpKeys.value.join(',');
    const response = await axios.delete(api.deleteBatch, {
      params: { ids },
      headers: { 'X-Access-Token': userStore.getToken },
    });
    if (response.data && response.data.success) {
      message.success('批量删除成功');
      selectedFollowUpKeys.value = [];
      selectedFollowUpRecord.value = null;
      followContentList.value = [];
      requirementPersonList.value = [];
      fetchFollowUpList();
    } else {
      message.error(response.data.message || '批量删除失败');
    }
  } catch (e) {
    console.error('批量删除失败', e);
    message.error('批量删除失败');
  } finally {
    loading.value = false;
  }
};



// 获取跟进记录列表
const loadFollowContents = async () => {
  if (!selectedFollowUpRecord.value) return;

  try {
    contentLoading.value = true;
    const response = await axios.get(api.followUpContentList, {
      params: { id: selectedFollowUpRecord.value.id },
      headers: { 'X-Access-Token': userStore.getToken },
    });

    if (response.data.success) {
      followContentList.value = response.data.result || [];
      contentPagination.total = followContentList.value.length;
    } else {
      message.error(response.data.message || '获取跟进记录失败');
    }
  } catch (error) {
    
    message.error('获取跟进记录失败');
  } finally {
    contentLoading.value = false;
  }
};

// 获取跟进计划文件列表
const getFollowPlanFiles = async (followPlanId) => {
  try {
    const response = await axios.get(api.getFollowPlanFiles, {
      params: { followPlanId },
      headers: { 'X-Access-Token': userStore.getToken },
    });

    if (response.data.success) {
      return response.data.result || [];
    }
    return [];
  } catch (error) {
    console.error('获取跟进计划文件失败:', error);
    return [];
  }
};



// 搜索
const handleSearch = () => {
  pagination.current = 1;
  fetchFollowUpList();
};

// 清空搜索
const handleClear = () => {
  searchParams.value = {
    customerName: '',
    followUpStatus: undefined,
    dateRange: [],
  };
  pagination.current = 1;
  fetchFollowUpList();
};

// 获取产品类别列表
const fetchProductTypes = async () => {
  try {
    productTypeLoading.value = true;
    const response = await axios.get(api.getProductTypes, {
      headers: { 
        'X-Access-Token': userStore.getToken,
        'Cache-Control': 'no-cache',
        'Pragma': 'no-cache'
      },
      // 添加时间戳参数来防止缓存
      params: { _t: new Date().getTime() }
    });
    
    if (response.data.success) {
      productTypeList.value = response.data.result || [];
    } else {
      message.error(response.data.message || '获取产品类别失败');
      productTypeList.value = [];
    }
  } catch (error) {
    console.error('获取产品类别失败:', error);
    // 详细输出错误信息以便调试
    if (error.response) {
      // 服务器响应了但状态码不在 2xx 范围内
      console.error('错误状态码:', error.response.status);
      console.error('错误数据:', error.response.data);
      console.error('错误头信息:', error.response.headers);
      message.error(`获取产品类别失败: 状态码 ${error.response.status}`);
    } else if (error.request) {
      // 请求已经发出，但没收到响应
      console.error('无响应:', error.request);
      message.error('获取产品类别失败: 服务器无响应');
    } else {
      // 其他错误
      console.error('错误信息:', error.message);
      message.error(`获取产品类别失败: ${error.message}`);
    }
    productTypeList.value = [];
  } finally {
    productTypeLoading.value = false;
  }
};

// 根据产品类别ID获取产品名称列表
const fetchProductName = async (productTypeId) => {
  if (!productTypeId) {
    productNameList.value = [];
    return;
  }
  
  try {
    productNameLoading.value = true;
    const response = await axios.get(api.getProductName, {
      params: { 
        productTypeId,
        _t: new Date().getTime() // 添加时间戳参数来防止缓存
      },
      headers: { 
        'X-Access-Token': userStore.getToken,
        'Cache-Control': 'no-cache',
        'Pragma': 'no-cache'
      },
    });
        console.log("传入的productTypeId", productTypeId)
    

    if (response.data.success) {
      productNameList.value = response.data.result || [];

      // 如果有待匹配的产品名称，自动匹配并填充到表单
      if (currentFollowUp.value.pendingProductNames && currentFollowUp.value.pendingProductNames.length > 0) {
        const productIds = [];
        currentFollowUp.value.pendingProductNames.forEach(name => {
          const product = productNameList.value.find(p => p.productName === name);
          if (product) {
            productIds.push(product.id);
          }
        });
        currentFollowUp.value.productNameIds = productIds;
        // 同步名称数组，确保提交时有 productName
        currentFollowUp.value.productName = [...currentFollowUp.value.pendingProductNames];
        // 清除待匹配的产品名称
        delete currentFollowUp.value.pendingProductNames;
      }
    } else {
      message.error(response.data.message || '获取产品名称失败');
      productNameList.value = [];
    }
  } catch (error) {
    console.error('获取产品名称失败:', error);
    // 详细输出错误信息以便调试
    if (error.response) {
      // 服务器响应了但状态码不在 2xx 范围内
      console.error('错误状态码:', error.response.status);
      console.error('错误数据:', error.response.data);
      console.error('错误头信息:', error.response.headers);
      message.error(`获取产品名称失败: 状态码 ${error.response.status}`);
    } else if (error.request) {
      // 请求已经发出，但没收到响应
      console.error('无响应:', error.request);
      message.error('获取产品名称失败: 服务器无响应');
    } else {
      // 其他错误
      console.error('错误信息:', error.message);
      message.error(`获取产品名称失败: ${error.message}`);
    }
    productNameList.value = [];
  } finally {
    productNameLoading.value = false;
  }
};

// 处理产品类别选择变化（编辑模式下不允许修改，始终使用主表值）
const handleProductTypeChange = (value) => {
  if (isEditMode.value) return;
  // 清空产品名称列表
  currentFollowUp.value.productNameIds = [];
  currentFollowUp.value.productName = [];

  // 如果选中了产品类别，获取对应的产品名称
  if (value) {
    const selectedType = productTypeList.value.find(item => item.id === value);
    if (selectedType) {
      currentFollowUp.value.productTypeId = selectedType.id;
      currentFollowUp.value.productType = selectedType.productType;
      fetchProductName(selectedType.id);
    }
  } else {
    productNameList.value = [];
  }
};

// 通用的产品名称处理函数
const processProductNameString = (productNameStr) => {
  if (!productNameStr) return [];

  console.log('处理产品名称字符串:', productNameStr);

  // 转换为字符串并去除首尾空格
  let cleanText = productNameStr.toString().trim();

  // 去除开头的 [ 和结尾的 ]
  if (cleanText.startsWith('[')) {
    cleanText = cleanText.substring(1);
  }
  if (cleanText.endsWith(']')) {
    cleanText = cleanText.substring(0, cleanText.length - 1);
  }

  console.log('清理后的产品名称字符串:', cleanText);

  // 按逗号分割并清理空格
  const productNames = cleanText.split(',').map(name => name.trim()).filter(name => name);

  console.log('分割后的产品名称数组:', productNames);

  return productNames;
};

// 处理产品名称选择变化（多选，编辑模式下不允许修改）
const handleProductNameChange = (values) => {
  if (isEditMode.value) return;
  if (values && values.length > 0) {
    // 根据选中的ID获取对应的产品名称
    const selectedProducts = productNameList.value.filter(item => values.includes(item.id));
    const productName = selectedProducts.map(item => item.productName);

    currentFollowUp.value.productNameIds = values;
    currentFollowUp.value.productName = productName;
  } else {
    currentFollowUp.value.productNameIds = [];
    currentFollowUp.value.productName = [];
  }
};

// 获取客户列表
const fetchCustomers = async () => {
  try {
    customerLoading.value = true;
    const response = await axios.get(api.getCustomers, {
      headers: { 
        'X-Access-Token': userStore.getToken,
        'Cache-Control': 'no-cache',
        'Pragma': 'no-cache'
      },
      // 添加时间戳参数来防止缓存
      params: { _t: new Date().getTime() }
    });
    
    console.log("获取到的客户列表", response)
    if (response.data.success) {
      // 处理Map类型的数据
      const customersData = response.data.result || {};

      
      customerList.value = response.data.result;
    } else {

      message.error(response.data.message || '获取客户列表失败');
      customerList.value = [];
    }
  } catch (error) {
    console.error('获取客户列表失败:', error);
    // 详细输出错误信息以便调试
    if (error.response) {
      console.error('错误状态码:', error.response.status);
      console.error('错误数据:', error.response.data);
      console.error('错误头信息:', error.response.headers);
      message.error(`获取客户列表失败: 状态码 ${error.response.status}`);
    } else if (error.request) {
      console.error('无响应:', error.request);
      message.error('获取客户列表失败: 服务器无响应');
    } else {
      console.error('错误信息:', error.message);
      message.error(`获取客户列表失败: ${error.message}`);
    }
    customerList.value = [];
  } finally {
    customerLoading.value = false;
  }
};

// 处理客户选择变化
const handleCustomerChange = (value) => {
  if (value) {
    const selectedCustomer = customerList.value.find(item => item.id === value);
    if (selectedCustomer) {
      currentFollowUp.value.customerId = selectedCustomer.id;
      currentFollowUp.value.customerName = selectedCustomer.customerName;
    }
  }
};

// 客户跟进操作
const handleAdd = async () => {
  currentFollowUp.value = {
    productNameId: [],
    productName: []
  };
  followUpModalTitle.value = '新增客户跟进';
  isView.value = false;
  isEditMode.value = false;

  // 获取客户列表
  await fetchCustomers();

  // 获取产品类别列表
  await fetchProductTypes();

  followUpModalVisible.value = true;
};

const handleEdit = async (record) => {
  currentFollowUp.value = { ...record };
  isEditMode.value = true;

  // 处理产品名称数据：确保productNameIds是数组
  if (record.productNameIds) {
    if (typeof record.productNameIds === 'string') {
      try {
        currentFollowUp.value.productNameIds = JSON.parse(record.productNameIds);
      } catch (e) {
        // 如果解析失败，按逗号分割
        currentFollowUp.value.productNameIds = record.productNameIds.split(',').map(id => id.trim()).filter(id => id);
      }
    } else if (Array.isArray(record.productNameIds)) {
      currentFollowUp.value.productNameIds = record.productNameIds;
    } else {
      currentFollowUp.value.productNameIds = [];
    }
  } else {
    currentFollowUp.value.productNameIds = [];
  }

  // 处理产品名称显示数据：处理后端返回的带中括号的逗号分隔字符串
  if (record.productName) {
    if (typeof record.productName === 'string') {
      console.log('编辑时原始产品名称数据:', record.productName);

      // 使用通用函数处理产品名称字符串
      const productNames = processProductNameString(record.productName);

      currentFollowUp.value.productNames = productNames;

      // 根据产品名称查找对应的ID并自动填充到表单
      if (productNameList.value.length > 0) {
        const productIds = [];
        productNames.forEach(name => {
          const product = productNameList.value.find(p => p.productName === name);
          if (product) {
            productIds.push(product.id);
          }
        });
        currentFollowUp.value.productNameIds = productIds;
        console.log('编辑时匹配到的产品ID:', productIds);
      } else {
        // 如果产品列表还没加载，先保存产品名称，稍后在产品列表加载完成后匹配
        currentFollowUp.value.productNameIds = [];
        currentFollowUp.value.pendingProductNames = productNames; // 临时保存待匹配的产品名称
        console.log('编辑时产品列表未加载，保存待匹配产品名称:', productNames);
      }
    } else if (Array.isArray(record.productName)) {
      currentFollowUp.value.productNames = record.productName;
      currentFollowUp.value.productNameIds = [];
    } else {
      currentFollowUp.value.productNames = [];
      currentFollowUp.value.productNameIds = [];
    }
  } else {
    currentFollowUp.value.productNames = [];
    currentFollowUp.value.productNameIds = [];
  }

  followUpModalTitle.value = '编辑客户跟进';
  isView.value = false;

  // 获取客户列表
  await fetchCustomers();

  // 获取产品类别列表
  await fetchProductTypes();

  // 如果有产品类别ID，获取对应的产品名称
  if (record.productTypeId) {
    await fetchProductName(record.productTypeId);
  }

  followUpModalVisible.value = true;
};

const handleView = async (record) => {
  currentFollowUp.value = { ...record };
  followUpModalTitle.value = '查看客户跟进';
  isView.value = true;
  
  // 获取客户列表
  await fetchCustomers();
  
  followUpModalVisible.value = true;
};

const handleDelete = async (record) => {
  try {
    loading.value = true;
    const response = await axios.delete(api.delete, {
      params: { id: record.id },
      headers: { 'X-Access-Token': userStore.getToken },
    });

    if (response.data.success) {
      message.success('删除成功');
      fetchFollowUpList();
    } else {
      message.error(response.data.message || '删除失败');
    }
  } catch (error) {
    console.error('删除失败:', error);
    message.error('删除失败');
  } finally {
    loading.value = false;
  }
};

const handleFollowUpSave = async () => {
  try {
    // 编辑模式下绕过对产品名称/类别的前端校验（以主表为准）
    if (!isEditMode.value) {
      await followUpFormRef.value.validate();
    }
    loading.value = true;
      // 处理跟进限时，确保是整数类型
    let deadLineInt = null;
    if (currentFollowUp.value.deadLine) {
      // 转换为整数
      deadLineInt = parseInt(currentFollowUp.value.deadLine, 10);
      if (isNaN(deadLineInt)) {
        deadLineInt = null;
      }
    }
    // 准备提交的数据
    const submitData = {
      ...currentFollowUp.value,
      isDeleted: currentFollowUp.value.isDeleted || 0,
      createTime: currentFollowUp.value.createTime || new Date().toISOString().split('T')[0],
      deadLine: deadLineInt,
      // 确保产品名称数据以数组形式发送给后端
      productNameIds: currentFollowUp.value.productNameIds || [],
      productName: currentFollowUp.value.productName || []
    };

    // 编辑模式下，强制使用主表已有的产品类型与产品名称，禁止被前端修改
    if (currentFollowUp.value.id) {
      submitData.productType = currentFollowUp.value.productType; // 名称
      submitData.productTypeId = currentFollowUp.value.productTypeId; // ID
      submitData.productName = Array.isArray(currentFollowUp.value.productName)
        ? currentFollowUp.value.productName
        : submitData.productName; // 保持主表数组
      submitData.productNameIds = Array.isArray(currentFollowUp.value.productNameIds)
        ? currentFollowUp.value.productNameIds
        : submitData.productNameIds;
      // 后端有时仅校验 productNameIds，确保两者一致
      if (!submitData.productNameIds?.length && Array.isArray(submitData.productName) && submitData.productName.length) {
        // 若仅有名称数组，尝试通过当前 productNameList 映射为ID
        const mapped = submitData.productName
          .map((n) => productNameList.value.find((p) => p.productName === n)?.id)
          .filter(Boolean);
        if (mapped.length) submitData.productNameIds = mapped;
      }
    }
    const url = currentFollowUp.value.id ? api.edit : api.add;

    // 控制台输出接口和数据
    console.log('保存客户跟进，接口地址:', url);
    console.log('提交的数据:', submitData);

    const response = await axios.post(url, submitData, {
      headers: { 'X-Access-Token': userStore.getToken },
    });

    

    if (response.data.success) {
      message.success(currentFollowUp.value.id ? '编辑成功' : '新增成功');
      followUpModalVisible.value = false;
      fetchFollowUpList();
    } else {
      message.error(response.data.message || '保存失败');
    }
  } catch (error) {
    console.error('保存失败:', error);
    // 放宽编辑模式下产品名称必选的提示
    if (isEditMode.value && (error?.response?.data?.message || '').includes('产品名称')) {
      message.error('编辑模式下已沿用主表产品名称，请刷新后重试');
    } else if (error?.response) {
      console.error('错误响应:', error.response.data);
      message.error(error.response.data.message || '保存失败');
    } else {
      message.error('保存失败');
    }
  } finally {
    loading.value = false;
  }
};

// 跟进计划操作
const handleAddPlan = () => {
  if (!selectedFollowUpRecord.value) {
    message.warning('请先选择一条客户跟进记录');
    return;
  }
  currentPlan.value = { 
    followUpId: selectedFollowUpRecord.value.id,
    followUpText: '',
    nextFollowTime: null
  };
  planModalTitle.value = '新增跟进计划';
  isView.value = false;
  planModalVisible.value = true;
};

const handleEditPlan = (record) => {
  currentPlan.value = { ...record };
  
  // 转换日期对象，适用于日期选择器
  if (currentPlan.value.nextFollowTime) {
    currentPlan.value.nextFollowTime = dayjs(currentPlan.value.nextFollowTime);
  }
  
  planModalTitle.value = '编辑跟进计划';
  isView.value = false;
  planModalVisible.value = true;
};

const handleViewPlan = (record) => {
  currentPlan.value = { ...record };
  
  // 转换日期对象，适用于日期选择器
  if (currentPlan.value.nextFollowTime) {
    currentPlan.value.nextFollowTime = dayjs(currentPlan.value.nextFollowTime);
  }
  
  planModalTitle.value = '查看跟进计划';
  isView.value = true;
  planModalVisible.value = true;
};

const handleDeletePlan = async (record) => {
  try {
    planLoading.value = true;
    const response = await axios.post(api.deleteFollowPlan, {
      followPlanId: record.id,
    }, {
      headers: { 'X-Access-Token': userStore.getToken },
    });

    if (response.data.success) {
      message.success('删除成功');
      loadFollowPlans();
    } else {
      message.error(response.data.message || '删除失败');
    }
  } catch (error) {
    console.error('删除跟进计划失败:', error);
    message.error('删除失败');
  } finally {
    planLoading.value = false;
  }
};

const handlePlanSave = async () => {
  try {
    await planFormRef.value.validate();
    planLoading.value = true;

    
    
    // 确保followUpId存在
    if (!currentPlan.value.followUpId) {
      currentPlan.value.followUpId = selectedFollowUpId.value;
    }
    
    if (!currentPlan.value.followUpId) {
      message.error('缺少必要参数：followUpId');
      planLoading.value = false;
      return;
    }
    
    // 使用表单数据格式提交
    const formData = new URLSearchParams();
    
    // 添加关键参数
    formData.append('followUpId', currentPlan.value.followUpId);
    formData.append('followUpText', currentPlan.value.followUpText || '');
    
    // 处理下次跟进时间
    if (currentPlan.value.nextFollowTime) {
      // 发送时间戳格式，Java可以通过 new Date(timestamp) 创建日期对象
      const timestamp = dayjs.isDayjs(currentPlan.value.nextFollowTime) 
        ? currentPlan.value.nextFollowTime.valueOf()
        : dayjs(currentPlan.value.nextFollowTime).valueOf();
      
      formData.append('nextFollowTime', timestamp.toString());
      
      
      
    }
    
    // 如果是编辑模式，添加ID
    if (currentPlan.value.id) {
      formData.append('followPlanId', currentPlan.value.id);
    }
    

    const url = currentPlan.value.id ? api.editFollowPlan : api.addFollowPlan;

    
    const response = await axios.post(url, formData, {
      headers: { 
        'X-Access-Token': userStore.getToken,
        'Content-Type': 'application/x-www-form-urlencoded'
      }
    });
    


    if (response.data.success) {
      message.success(currentPlan.value.id ? '编辑成功' : '新增成功');
      planModalVisible.value = false;
      loadFollowPlans();
    } else {
      message.error(response.data.message || '保存失败');
    }
  } catch (error) {
    console.error('保存跟进计划失败:', error);
    if (error.response) {
      console.error('错误响应:', error.response.data);
      message.error(error.response.data.message || '保存失败');
    } else {
      message.error('保存失败: ' + error.message);
    }
  } finally {
    planLoading.value = false;
  }
};

// 跟进记录操作
const handleAddContent = () => {
  if (!selectedFollowUpRecord.value) {
    message.warning('请先选择一条客户跟进记录');
    return;
  }
  currentContent.value = { followUpId: selectedFollowUpRecord.value.id };
  contentModalTitle.value = '新增跟进记录';
  isView.value = false;
  contentModalVisible.value = true;
};

const handleEditContent = (record) => {
  console.log('编辑跟进记录数据:', record);

  // 处理后端返回的map集合数据
  currentContent.value = { ...record };

  // 处理日期字段
  if (currentContent.value.followUpTime) {
    currentContent.value.followUpTime = dayjs(currentContent.value.followUpTime);
  }
  if (currentContent.value.nextFollowTime) {
    currentContent.value.nextFollowTime = dayjs(currentContent.value.nextFollowTime);
  }

  contentModalTitle.value = '编辑跟进记录';
  isView.value = false;
  contentModalVisible.value = true;
};

const handleViewContent = (record) => {
  console.log('查看跟进记录数据:', record);

  // 处理后端返回的map集合数据
  currentContent.value = { ...record };

  // 处理日期字段
  if (currentContent.value.followUpTime) {
    currentContent.value.followUpTime = dayjs(currentContent.value.followUpTime);
  }
  if (currentContent.value.nextFollowTime) {
    currentContent.value.nextFollowTime = dayjs(currentContent.value.nextFollowTime);
  }

  contentModalTitle.value = '查看跟进记录';
  isView.value = true;
  contentModalVisible.value = true;
};

const handleDeleteContent = async (record) => {
  try {
    contentLoading.value = true;
    const response = await axios.post(api.deleteFollowUpContent, {
      id: record.id,
    }, {
      headers: { 'X-Access-Token': userStore.getToken },
    });

    if (response.data.success) {
      message.success('删除成功');
      loadFollowContents();
    } else {
      message.error(response.data.message || '删除失败');
    }
  } catch (error) {
    console.error('删除跟进记录失败:', error);
    message.error('删除失败');
  } finally {
    contentLoading.value = false;
  }
};

const handleContentSave = async () => {
  try {
    await contentFormRef.value.validate();
    contentLoading.value = true;


    // 处理日期格式
    let followUpTimeStr = '';
    if (currentContent.value.followUpTime) {
      if (dayjs.isDayjs(currentContent.value.followUpTime)) {
        followUpTimeStr = currentContent.value.followUpTime.format('YYYY-MM-DD');
      } else {
        followUpTimeStr = currentContent.value.followUpTime;
      }
    }

    if (currentContent.value.id) {
      // 编辑跟进记录 - 使用 JSON 格式
      const saveData = { ...currentContent.value };
      if (saveData.followUpTime && dayjs.isDayjs(saveData.followUpTime)) {
        saveData.followUpTime = saveData.followUpTime.format('YYYY-MM-DD');
      }

      const response = await axios.post(api.editFollowUpContent, saveData, {
        headers: { 'X-Access-Token': userStore.getToken },
      });

      if (response.data.success) {
        message.success('编辑成功');
        contentModalVisible.value = false;
        loadFollowContents();
        fetchUpcomingFollowUps(); // 刷新即将到期的跟进记录
      } else {
        message.error(response.data.message || '编辑失败');
      }
    } else {
      // 新增跟进记录 - 使用 @RequestParam 格式，传入所有表单数据
      const params = new URLSearchParams();

      // 必填参数
      params.append('followUpId', currentContent.value.followUpId || selectedFollowUpIdForContent.value);

      // 可选参数 - 传入所有表单字段
      params.append('customerClassification', currentContent.value.customerClassification || '');
      params.append('followUpDescription', currentContent.value.followUpDescription || '');
      params.append('timeConfirm', currentContent.value.timeConfirm || '');
      params.append('requirment', currentContent.value.requirment || '');
      params.append('potentialRequirment', currentContent.value.potentialRequirment || '');
      params.append('managementOpinion', currentContent.value.managementOpinion || '');
      params.append('businessOpinion', currentContent.value.bussinesOpinion || ''); // 前端字段名是bussinesOpinion，后端是businessOpinion
      params.append('technologyRecord', currentContent.value.technologyRecord || '');
      params.append('intention', currentContent.value.intention || '');
      params.append('otherDescription', currentContent.value.otherDescription || '');
      params.append('summarize', currentContent.value.summarize || '');

      // 处理下次跟进时间
      if (currentContent.value.nextFollowTime) {
        let nextFollowTimeStr = '';
        if (dayjs.isDayjs(currentContent.value.nextFollowTime)) {
          nextFollowTimeStr = currentContent.value.nextFollowTime.format('YYYY-MM-DD');
        } else {
          nextFollowTimeStr = currentContent.value.nextFollowTime;
        }
        params.append('nextFollowTime', nextFollowTimeStr);
      }

      console.log('新增跟进记录参数:', Object.fromEntries(params));

      const response = await axios.post(api.addFollowUpContent, params, {
        headers: {
          'X-Access-Token': userStore.getToken,
          'Content-Type': 'application/x-www-form-urlencoded'
        },
      });

      if (response.data.success) {
        message.success('新增成功');
        contentModalVisible.value = false;
        loadFollowContents();
        fetchUpcomingFollowUps(); // 刷新即将到期的跟进记录
      } else {
        message.error(response.data.message || '新增失败');
      }
    }
  } catch (error) {
    console.error('保存跟进记录失败:', error);
    if (error.response) {
      console.error('错误响应:', error.response.data);
      message.error(error.response.data.message || '保存失败');
    } else {
      message.error('保存失败');
    }
  } finally {
    contentLoading.value = false;
  }
};

// 文件操作
const handleUploadPlanFile = (record) => {
  currentUploadType.value = 'plan';
  currentUploadRecordId.value = record.id;
  fileUploadTitle.value = '上传跟进计划文件';
  fileUploadList.value = [];
  fileUploadModalVisible.value = true;
};


const handleBeforeUploadFile = (file) => {
  const isLt10M = file.size / 1024 / 1024 < 10;
  if (!isLt10M) {
    message.error('文件大小不能超过10MB!');
    return false;
  }
  return true;
};

const customUploadFile = async ({ file, onProgress, onSuccess, onError }) => {
  try {
    const formData = new FormData();
    formData.append('file', file);

    let uploadUrl = '';
    let paramName = '';

    if (currentUploadType.value === 'plan') {
      uploadUrl = api.uploadFollowPlanFile;
      paramName = 'followPlanId';
    } else {
      uploadUrl = api.uploadFollowUpFile;
      paramName = 'followUpContentId';
    }

    formData.append(paramName, currentUploadRecordId.value);

    const response = await axios.post(uploadUrl, formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
        'X-Access-Token': userStore.getToken,
      },
      onUploadProgress: (progressEvent) => {
        const percent = Math.round((progressEvent.loaded * 100) / progressEvent.total);
        onProgress({ percent });
      },
    });

    if (response.data.success) {
      onSuccess(response.data, file);
      message.success('文件上传成功');
    } else {
      onError(new Error(response.data.message || '上传失败'));
      message.error(response.data.message || '上传失败');
    }
  } catch (error) {
    console.error('文件上传失败:', error);
    onError(error);
    message.error('文件上传失败');
  }
};

const handleRemoveFile = (file) => {
  const index = fileUploadList.value.findIndex(item => item.uid === file.uid);
  if (index > -1) {
    fileUploadList.value.splice(index, 1);
  }
};

const handleFileUploadComplete = () => {
  fileUploadModalVisible.value = false;
  // 刷新对应的列表
  if (currentUploadType.value === 'plan') {
    loadFollowPlans();
  } else {
    loadFollowContents();
  }
};

const showFileDetail = (files, type) => {
  currentFiles.value = files || [];
  fileDetailModalVisible.value = true;
};

const handlePreviewFile = async (file) => {
  try {
    const response = await axios.get(api.previewFile, {
      params: { fileId: file.id },
      headers: { 'X-Access-Token': userStore.getToken },
      responseType: 'blob',
    });

    const blob = new Blob([response.data]);
    const url = window.URL.createObjectURL(blob);
    window.open(url, '_blank');
  } catch (error) {
    console.error('预览文件失败:', error);
    message.error('预览文件失败');
  }
};

const handleDownloadFile = async (file) => {
  try {
    const response = await axios.get(api.downloadFile, {
      params: { fileId: file.id },
      headers: { 'X-Access-Token': userStore.getToken },
      responseType: 'blob',
    });

    const blob = new Blob([response.data]);
    const url = window.URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.download = file.fileName || 'download';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    window.URL.revokeObjectURL(url);

    message.success('文件下载成功');
  } catch (error) {
    console.error('下载文件失败:', error);
    message.error('下载文件失败');
  }
};

const handleDeleteFile = async (file) => {
  try {
    const response = await axios.delete(api.deleteFile, {
      params: { fileId: file.id },
      headers: { 'X-Access-Token': userStore.getToken },
    });

    if (response.data.success) {
      message.success('删除文件成功');
      // 刷新文件列表
      const index = currentFiles.value.findIndex(item => item.id === file.id);
      if (index > -1) {
        currentFiles.value.splice(index, 1);
      }
      // 刷新对应的数据列表
      if (currentUploadType.value === 'plan') {
        loadFollowPlans();
      } else {
        loadFollowContents();
      }
    } else {
      message.error(response.data.message || '删除文件失败');
    }
  } catch (error) {
    console.error('删除文件失败:', error);
    message.error('删除文件失败');
  }
};

// 创建订单弹窗状态
const createOrderModalVisible = ref(false);
const createOrderSubmitting = ref(false);
const createOrderTitle = ref('创建订单');
const createOrderForm = ref({
  followUpId: '',
  customerId: '',
  customerName: '',
  productType: '',
});
const createOrderItems = ref([]); // { productId, productName, unit, quantity }

// 产品类型与名称映射
const productTypeIdMap = ref({}); // name -> id
const currentProductContexts = ref([]); // [{id, productName, unit, suggestedPrice, minimumPrice}]

// 加载产品类别列表，建立name->id映射
const ensureProductTypeMap = async () => {
  if (Object.keys(productTypeIdMap.value).length > 0) return;
  try {
    const res = await axios.get('/jeecg-boot/products/productType/getProductTypeNameAndId', {
      headers: { 'X-Access-Token': userStore.getToken },
    });
    if (res.data) {
      const list = Array.isArray(res.data) ? res.data : res.data.result || [];
      const map = {};
      list.forEach((it) => {
        if (it.productType && it.id) map[it.productType] = it.id;
      });
      productTypeIdMap.value = map;
    }
  } catch (e) {
    console.error('加载产品类别失败', e);
  }
};

// 根据产品类别名称加载该类别下的产品列表
const loadProductContextsByTypeName = async (typeName) => {
  await ensureProductTypeMap();
  const typeId = productTypeIdMap.value[typeName];
  if (!typeId) {
    currentProductContexts.value = [];
    return;
  }
  try {
    const res = await axios.get('/jeecg-boot/products/productType/getProductNameByProductTypeId', {
      params: { productTypeId: typeId },
      headers: { 'X-Access-Token': userStore.getToken },
    });
    const list = Array.isArray(res.data) ? res.data : res.data.result || [];
    currentProductContexts.value = list;
  } catch (e) {
    console.error('加载产品名称失败', e);
    currentProductContexts.value = [];
  }
};

// 打开创建订单弹窗
const openCreateOrderModal = async (record) => {
  // 将产品名称标准化为数组
  let productNames = [];
  if (Array.isArray(record.productName)) {
    productNames = record.productName;
  } else if (typeof record.productName === 'string') {
    try {
      const parsed = JSON.parse(record.productName);
      productNames = Array.isArray(parsed) ? parsed : [];
    } catch (e) {
      productNames = record.productName
        .split(',')
        .map((s) => s && s.trim())
        .filter(Boolean);
    }
  }

  await loadProductContextsByTypeName(record.productType);
  // 构建items，默认带出unit，找不到则空
  const ctxMapByName = {};
  currentProductContexts.value.forEach((c) => {
    ctxMapByName[c.productName] = c;
  });

  createOrderForm.value = {
    followUpId: record.id,
    customerId: record.customerId,
    customerName: record.customerName,
    productType: record.productType,
  };

  createOrderItems.value = productNames.map((name) => {
    const ctx = ctxMapByName[name];
    return {
      productId: ctx?.id,
      productName: name,
      unit: ctx?.unit || '',
      quantity: 1,
    };
  });

  createOrderTitle.value = `创建订单 - ${record.customerName}`;
  createOrderModalVisible.value = true;
};

// 确认创建订单
const handleConfirmCreateOrder = async () => {
  try {
    if (!createOrderItems.value.length) {
      message.warning('没有可提交的产品明细');
      return;
    }
    // 简单校验
    for (const item of createOrderItems.value) {
      if (!item.productName) return message.warning('产品名称不能为空');
      if (!item.quantity || item.quantity <= 0) return message.warning('数量必须大于0');
    }
    createOrderSubmitting.value = true;
    const payload = {
      ...createOrderForm.value,
      items: createOrderItems.value,
    };
    const resp = await axios.post('/jeecg-boot/followup/followUp/addOrder', payload, {
      headers: { 'X-Access-Token': userStore.getToken },
    });
    if (resp.data && resp.data.success) {
      message.success('创建订单成功');
      createOrderModalVisible.value = false;
      fetchFollowUpList();
    } else {
      message.error(resp.data.message || '创建订单失败');
    }
  } catch (e) {
    console.error('创建订单失败', e);
    message.error('创建订单失败');
  } finally {
    createOrderSubmitting.value = false;
  }
};

// 创建合同模态框操作
const handleProjectSave = async () => {
  try {
    await projectFormRef.value.validate();
    projectLoading.value = true;

    // 构建参数
    const params = {
      contractTheme: projectForm.value.contractTheme,
      customerName: projectForm.value.customerName,
      contractId: projectForm.value.contractId
    };

    // 在控制台输出准备传入的数据
    console.log('准备传入后端的JSON数据:', JSON.stringify(params, null, 2));
    console.log('调用接口:', api.followUpGenerateContract);

    const response = await axios.post(api.followUpGenerateContract, params, {
      headers: { 'X-Access-Token': userStore.getToken },
    });

    if (response.data.success) {
      message.success('创建合同成功');
      projectModalVisible.value = false;
      loadFollowContents(); // 刷新跟进记录列表
    } else {
      message.error(response.data.message || '创建合同失败');
    }
  } catch (error) {
    console.error('创建合同失败:', error);
    message.error('创建合同失败');
  } finally {
    projectLoading.value = false;
  }
};

// 获取需求人员列表
const loadRequirementPersons = async () => {
  if (!selectedFollowUpRecord.value || !selectedFollowUpRecord.value.customerId) {
    console.log('未选中记录或缺少customerId，清空需求人员列表');
    requirementPersonList.value = [];
    return;
  }

  try {
    requirementPersonLoading.value = true;
    console.log('开始调用getRequirementPersonList接口');
    console.log('接口地址:', api.getRequirementPersonList);
    console.log('传入参数 customerId:', selectedFollowUpRecord.value.customerId);
    
    const response = await axios.get(api.getRequirementPersonList, {
      params: { customerId: selectedFollowUpRecord.value.customerId },
      headers: { 'X-Access-Token': userStore.getToken },
    });

    console.log('getRequirementPersonList接口响应:', response.data);

    if (response.data.success) {
      requirementPersonList.value = response.data.result || [];
      requirementPersonPagination.total = requirementPersonList.value.length;
      console.log('获取到需求人员数据:', requirementPersonList.value);
      console.log('需求人员数量:', requirementPersonList.value.length);
    } else {
      message.error(response.data.message || '获取需求人员失败');
      requirementPersonList.value = [];
    }
  } catch (error) {
    console.error('获取需求人员失败:', error);
    if (error.response) {
      console.error('错误响应状态码:', error.response.status);
      console.error('错误响应数据:', error.response.data);
    }
    message.error('获取需求人员失败');
    requirementPersonList.value = [];
  } finally {
    requirementPersonLoading.value = false;
  }
};

// 查看需求人员详情
const handleViewRequirementPerson = (record) => {
  // 显示详情对话框
  message.info(`需求人员详情: 
    角色: ${record.developRole || '无角色'}, 
    邮箱: ${record.email || '无邮箱'}, 
    创建人: ${record.createBy || '无创建人'}, 
    创建时间: ${record.createTime ? dayjs(record.createTime).format('YYYY-MM-DD HH:mm:ss') : '无创建时间'}, 
    更新人: ${record.updateBy || '无更新人'}, 
    更新时间: ${record.updateTime ? dayjs(record.updateTime).format('YYYY-MM-DD HH:mm:ss') : '无更新时间'}, 
    所属部门: ${record.sysOrgCode || '无所属部门'}`
  );
};

// 部门和用户数据
const departList = ref([]);
const userList = ref([]);
const roleOptions = [
  { value: '商务跟进人员', label: '商务跟进人员' },
  { value: '技术支持人员', label: '技术支持人员' },
  { value: '商务管理人员', label: '商务管理人员' },
  { value: '技术管理人员', label: '技术管理人员' },
];

// 获取所有部门信息
const fetchAllDepartments = async () => {
  try {
    const response = await axios.get(api.getAllDepart, {
      headers: { 'X-Access-Token': userStore.getToken },
    });
    console.log("获取所有部门相应： ",response)
    if (response.data.success) {
      departList.value = response.data.result || [];
    } else {
      message.error(response.data.message || '获取部门信息失败');
      departList.value = [];
    }
  } catch (error) {
    console.error('获取部门信息失败:', error);
    message.error('获取部门信息失败');
    departList.value = [];
  }
};

// 根据部门ID获取用户列表
const fetchUsersByDepartId = async (departId) => {
  try {
    const response = await axios.get(api.getUserByDepartId, {
      params: { id: departId },
      headers: { 'X-Access-Token': userStore.getToken },
    });

    if (response.data.success) {
      userList.value = response.data.result || [];
    } else {
      message.error(response.data.message || '获取部门人员失败');
      userList.value = [];
    }
  } catch (error) {
    console.error('获取部门人员失败:', error);
    message.error('获取部门人员失败');
    userList.value = [];
  }
};

// 处理部门选择变化
const handleDepartmentChange = (value, option) => {
  if (value) {
    const selectedDepart = departList.value.find(item => item.id === value || item.departName === value);
    if (selectedDepart) {
      fetchUsersByDepartId(selectedDepart.id, selectedDepart.departName);
      requirementPersonForm.value.departId = selectedDepart.id;
      requirementPersonForm.value.departName = selectedDepart.departName;
    }
  } else {
    userList.value = [];
    requirementPersonForm.value.userId = undefined;
    requirementPersonForm.value.realName = undefined;
  }
};

// 处理用户选择变化
const handleUserChange = (value, option) => {
  if (value) {
    const selectedUser = userList.value.find(item => item.id === value);
    if (selectedUser) {
      requirementPersonForm.value.userId = selectedUser.id;
      requirementPersonForm.value.realName = selectedUser.realName;
    }
  }
};

// 新增需求人员
const handleAddRequirementPerson = async () => {
  if (!selectedFollowUpRecord.value || !selectedFollowUpRecord.value.customerId) {
    message.warning('请先选择一条客户跟进记录');
    return;
  }
  
  // 初始化表单
  requirementPersonForm.value = {
    customerId: selectedFollowUpRecord.value.customerId,
  };
  
  // 获取部门信息
  await fetchAllDepartments();
  
  requirementPersonModalTitle.value = '新增需求人员';
  requirementPersonModalVisible.value = true;
};

// 编辑需求人员
const handleEditRequirementPerson = async (record) => {
  requirementPersonForm.value = { ...record };
  requirementPersonModalTitle.value = '编辑需求人员';
  requirementPersonModalVisible.value = true;
  
  // 获取部门信息
  await fetchAllDepartments();
  
  // 如果有部门ID，获取该部门的用户
  if (record.departId) {
    await fetchUsersByDepartId(record.departId, record.departName);
  }
};

// 删除需求人员
const handleDeleteRequirementPerson = async (record) => {
  try {
    requirementPersonLoading.value = true;
    const response = await axios.delete(api.deleteRequirementPerson, {
      params: { id: record.id },
      headers: { 'X-Access-Token': userStore.getToken },
    });

    if (response.data.success) {
      message.success('删除成功');
      loadRequirementPersons();
    } else {
      message.error(response.data.message || '删除失败');
    }
  } catch (error) {
    console.error('删除需求人员失败:', error);
    message.error('删除失败');
  } finally {
    requirementPersonLoading.value = false;
  }
};

// 保存需求人员
const handleRequirementPersonSave = async () => {
  try {
    await requirementPersonFormRef.value.validate();
    requirementPersonLoading.value = true;
    
    // 准备提交的数据
    const submitData = {
      id: requirementPersonForm.value.customerId, // 使用customerId作为id
      userId: requirementPersonForm.value.userId,
      developRole: requirementPersonForm.value.developRole
    };

    const response = await assignBusinessDeptUser2(submitData);
    
    console.log("response ",response)
    if (response.success) {
      message.success('保存成功');
      requirementPersonModalVisible.value = false;
      loadRequirementPersons();
    } else {
      message.error(response.data.message || '保存失败');
    }
  } catch (error) {
    console.error('保存需求人员失败:', error);
    if (error.response) {
      message.error(error.response.data.message || '保存失败');
    } else {
      message.error('不能重复添加');
    }
  } finally {
    requirementPersonLoading.value = false;
  }
};

// 修改跟进状态相关函数
const handleUpdateFollowUpStatus = () => {
  if (!selectedFollowUpRecord.value) {
    message.warning('请先选择一条客户跟进记录');
    return;
  }

  // 初始化表单数据，设置当前的跟进状态
  updateStatusForm.value = {
    id: selectedFollowUpRecord.value.id,
    followUpStatus: selectedFollowUpRecord.value.followUpStatus || ''
  };

  updateStatusModalVisible.value = true;
};

const handleUpdateStatusSave = async () => {
  try {
    await updateStatusFormRef.value.validate();
    updateStatusLoading.value = true;

    // 构建更新数据：包含完整的行数据，只修改 followUpStatus
    const updateData = {
      ...selectedFollowUpRecord.value, // 展开完整的行数据
      followUpStatus: updateStatusForm.value.followUpStatus // 只更新跟进状态
    };

    console.log('准备更新跟进状态，完整数据:', updateData);

    // 调用主表的修改接口
    const response = await axios.post(api.editFollowStatus, updateData, {
      headers: { 'X-Access-Token': userStore.getToken },
    });

    if (response.data.success) {
      message.success('跟进状态修改成功');
      updateStatusModalVisible.value = false;
      // 刷新跟进列表
      fetchFollowUpList();
    } else {
      message.error(response.data.message || '跟进状态修改失败');
    }
  } catch (error) {
    console.error('修改跟进状态失败:', error);
    message.error('修改跟进状态失败，请稍后重试');
  } finally {
    updateStatusLoading.value = false;
  }
};

// 页面初始化
onMounted(() => {
  fetchFollowUpList();
  fetchUpcomingFollowUps(); // 获取即将到期的跟进记录
});
</script>

<style scoped>
.filter-container {
  background: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

/* 提醒通知区域样式 */
.reminder-notification {
  margin-bottom: 16px;
}

.reminder-alert {
  border-left: 4px solid #faad14;
  background: #fffbe6;
  border-color: #ffe58f;
}

.upcoming-list {
  margin-top: 8px;
}

.upcoming-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 6px 12px;
  margin-bottom: 4px;
  background: #fff;
  border-radius: 4px;
  border: 1px solid #e8e8e8;
  cursor: pointer;
  transition: all 0.3s;
}

.upcoming-item:hover {
  background: #f0f2ff;
  border-color: #1890ff;
  transform: translateY(-1px);
  box-shadow: 0 2px 4px rgba(24, 144, 255, 0.2);
}

.customer-name {
  font-weight: 500;
  color: #333;
}

.due-time {
  font-size: 12px;
  color: #fa8c16;
  font-weight: 500;
}

.more-count {
  text-align: center;
  color: #666;
  font-size: 12px;
  margin-top: 4px;
}

.filter-item {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
  flex-wrap: wrap;
  gap: 10px;
}

.table-container {
  background: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  margin-top: 16px;
}

.table-row-light {
  background-color: #fafafa;
}

.table-row-dark {
  background-color: #ffffff;
}

.file-upload-container {
  padding: 20px;
}

.file-upload-actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  margin-top: 20px;
}

.file-detail-container {
  max-height: 400px;
  overflow-y: auto;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .filter-item {
    flex-direction: column;
    align-items: stretch;
  }

  .filter-item > * {
    width: 100%;
    margin-bottom: 10px;
  }

  .table-container {
    padding: 10px;
  }
}

/* 表格样式优化 */
:deep(.ant-table) {
  font-size: 14px;
}

:deep(.ant-table-thead > tr > th) {
  background-color: #f5f5f5;
  font-weight: 600;
  text-align: center;
}

:deep(.ant-table-tbody > tr > td) {
  text-align: center;
  padding: 12px 8px;
}

:deep(.ant-table-tbody > tr:hover > td) {
  background-color: #e6f7ff;
}

/* 按钮样式 */
.ant-btn {
  border-radius: 6px;
  font-weight: 500;
}

.ant-btn-primary {
  background: linear-gradient(135deg, #1890ff 0%, #096dd9 100%);
  border: none;
  box-shadow: 0 2px 4px rgba(24, 144, 255, 0.3);
}

.ant-btn-primary:hover {
  background: linear-gradient(135deg, #40a9ff 0%, #1890ff 100%);
  transform: translateY(-1px);
  box-shadow: 0 4px 8px rgba(24, 144, 255, 0.4);
}

/* 模态框样式 */
:deep(.ant-modal-header) {
  background: linear-gradient(135deg, #f0f9ff 0%, #e6f7ff 100%);
  border-bottom: 1px solid #d9d9d9;
}

:deep(.ant-modal-title) {
  color: #1890ff;
  font-weight: 600;
}

/* 表单样式 */
:deep(.ant-form-item-label > label) {
  font-weight: 500;
  color: #262626;
}

:deep(.ant-input) {
  border-radius: 6px;
}

:deep(.ant-select-selector) {
  border-radius: 6px;
}

/* 标签页样式 */
:deep(.ant-tabs-tab) {
  font-weight: 500;
  padding: 12px 24px;
}

:deep(.ant-tabs-tab-active) {
  color: #1890ff;
}

:deep(.ant-tabs-ink-bar) {
  background: linear-gradient(135deg, #1890ff 0%, #096dd9 100%);
  height: 3px;
}

/* 上传组件样式 */
:deep(.ant-upload-drag) {
  border: 2px dashed #d9d9d9;
  border-radius: 8px;
  background: #fafafa;
  transition: all 0.3s ease;
}

:deep(.ant-upload-drag:hover) {
  border-color: #1890ff;
  background: #f0f9ff;
}

:deep(.ant-upload-drag.ant-upload-drag-hover) {
  border-color: #1890ff;
  background: #f0f9ff;
}

/* 分页样式 */
:deep(.ant-pagination) {
  margin-top: 20px;
  text-align: right;
}

:deep(.ant-pagination-item-active) {
  background: #1890ff;
  border-color: #1890ff;
}

:deep(.ant-pagination-item-active a) {
  color: #fff;
}

/* 跟进记录模态框美化样式 */
.follow-up-modal {
  .modal-content-wrapper {
    max-height: 80vh;
    overflow-y: auto;
    padding: 0;
  }

  .follow-up-form {
    .form-section-card {
      margin-bottom: 20px;
      border-radius: 12px;
      box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
      transition: all 0.3s ease;

      &:hover {
        box-shadow: 0 4px 16px rgba(0, 0, 0, 0.12);
      }

      :deep(.ant-card-head) {
        background: linear-gradient(135deg, #f8faff 0%, #f0f7ff 100%);
        border-bottom: 2px solid #e6f4ff;
        border-radius: 12px 12px 0 0;

        .ant-card-head-title {
          color: #1890ff;
          font-weight: 600;
          font-size: 16px;
          display: flex;
          align-items: center;

          &:before {
            content: '';
            width: 4px;
            height: 20px;
            background: linear-gradient(135deg, #1890ff 0%, #096dd9 100%);
            margin-right: 12px;
            border-radius: 2px;
          }
        }
      }

      :deep(.ant-card-body) {
        padding: 24px;
        background: #fff;
      }
    }

    .custom-select {
      .select-option-content {
        display: flex;
        align-items: center;
        gap: 8px;
      }

      :deep(.ant-select-selector) {
        border: 2px solid #f0f0f0;
        border-radius: 8px;
        transition: all 0.3s ease;
        box-shadow: 0 2px 4px rgba(0, 0, 0, 0.02);

        &:hover {
          border-color: #40a9ff;
          box-shadow: 0 2px 8px rgba(64, 169, 255, 0.1);
        }
      }

      :deep(.ant-select-focused .ant-select-selector) {
        border-color: #1890ff !important;
        box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2) !important;
      }
    }

    .custom-date-picker {
      :deep(.ant-picker) {
        border: 2px solid #f0f0f0;
        border-radius: 8px;
        transition: all 0.3s ease;
        box-shadow: 0 2px 4px rgba(0, 0, 0, 0.02);

        &:hover {
          border-color: #40a9ff;
          box-shadow: 0 2px 8px rgba(64, 169, 255, 0.1);
        }

        &.ant-picker-focused {
          border-color: #1890ff !important;
          box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2) !important;
        }
      }
    }

    .custom-textarea {
      :deep(.ant-input) {
        border: 2px solid #f0f0f0;
        border-radius: 8px;
        transition: all 0.3s ease;
        box-shadow: 0 2px 4px rgba(0, 0, 0, 0.02);
        font-size: 14px;
        line-height: 1.6;

        &:hover {
          border-color: #40a9ff;
          box-shadow: 0 2px 8px rgba(64, 169, 255, 0.1);
        }

        &:focus {
          border-color: #1890ff !important;
          box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2) !important;
        }

        &::placeholder {
          color: #bfbfbf;
          font-style: italic;
        }
      }
    }
  }

  .modal-footer-wrapper {
    display: flex;
    justify-content: flex-end;
    gap: 12px;
    padding: 16px 0 0 0;
    border-top: 1px solid #f0f0f0;

    .cancel-btn {
      border: 2px solid #d9d9d9;
      color: #595959;
      border-radius: 8px;
      font-weight: 500;
      transition: all 0.3s ease;

      &:hover {
        border-color: #40a9ff;
        color: #40a9ff;
        transform: translateY(-1px);
        box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
      }
    }

    .save-btn {
      background: linear-gradient(135deg, #1890ff 0%, #096dd9 100%);
      border: none;
      border-radius: 8px;
      font-weight: 500;
      box-shadow: 0 4px 12px rgba(24, 144, 255, 0.3);
      transition: all 0.3s ease;

      &:hover {
        background: linear-gradient(135deg, #40a9ff 0%, #1890ff 100%);
        transform: translateY(-2px);
        box-shadow: 0 6px 16px rgba(24, 144, 255, 0.4);
      }

      &:active {
        transform: translateY(0);
      }
    }
  }
}

/* 模态框头部美化 */
:deep(.follow-up-modal .ant-modal-header) {
  background: linear-gradient(135deg, #f8faff 0%, #e6f4ff 100%);
  border-bottom: 2px solid #d6e4ff;
  border-radius: 8px 8px 0 0;
  padding: 20px 24px;

  .ant-modal-title {
    color: #1890ff;
    font-size: 18px;
    font-weight: 600;
    display: flex;
    align-items: center;

    &:before {
      content: '📝';
      margin-right: 12px;
      font-size: 20px;
    }
  }
}

:deep(.follow-up-modal .ant-modal-body) {
  padding: 24px;
  background: #fafbfc;
}

:deep(.follow-up-modal .ant-modal-footer) {
  background: #fff;
  border-top: 2px solid #f0f0f0;
  padding: 16px 24px;
  border-radius: 0 0 8px 8px;
}

/* 表单标签美化 */
:deep(.follow-up-form .ant-form-item-label > label) {
  font-weight: 600;
  color: #262626;
  font-size: 14px;
  
  &:after {
    content: '';
    margin-left: 4px;
  }

  &.ant-form-item-required:before {
    color: #ff4d4f;
    font-size: 16px;
    margin-right: 6px;
  }
}

/* 响应式设计 */
@media (max-width: 1400px) {
  .follow-up-modal {
    :deep(.ant-modal) {
      max-width: 95vw;
      margin: 10px auto;
    }
  }
}

@media (max-width: 768px) {
  .follow-up-modal {
    .follow-up-form {
      .form-section-card {
        :deep(.ant-card-body) {
          padding: 16px;
        }
      }
    }
  }
}
</style>

